//
//  GroupMembersViewController.m
//  Assistant
//
//  Created by Hunk on 12-2-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "GroupMembersViewController.h"
#import "AddressBookPerson.h"
#import "PinYin.h"
#import "AddressBookManager.h"
#import "UIStatusWindow.h"

#define TAG_TOOLBARVIEW (11)

@interface GroupMembersViewController (Private)

- (AddressBookPerson *)personForGroupAtIndexPath:(NSIndexPath *)indexPath;

- (BOOL)searchResult:(NSString*)personName searchText:(NSString *)searchText;

- (NSString*)getFirstLetterOfPersonName:(NSString*)strPersonName;

- (void)initGroupMembers:(NSArray *)groupMembersArray;

@end

@implementation GroupMembersViewController
@synthesize addressBookGroup = _addressBookGroup;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    SAFE_RELEASE(_tableView)
    SAFE_RELEASE(_footerView)
    SAFE_RELEASE(_addressBookGroup)
    SAFE_RELEASE(_groupMembersArray)
    SAFE_RELEASE(_groupMembersDictionary)
    SAFE_RELEASE(_sectionTitleArray)
    SAFE_RELEASE(_checkmarkDictionary)
    SAFE_RELEASE(_selectedMemberArray)
    SAFE_RELEASE(_abPersonViewController)
    
    [super dealloc];
}

- (id)init
{
    if((self = [super init]))
    {
        // Init data
        _groupMembersArray      = [[NSMutableArray alloc] init];
        _groupMembersDictionary = [[NSMutableDictionary alloc] init];
        _sectionTitleArray      = [[NSMutableArray alloc] init];
        _checkmarkDictionary    = [[NSMutableDictionary alloc] init];
        _selectedMemberArray    = [[NSMutableArray alloc] init];
        _selectedAll            = NO;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self initGroupMembers:_groupMembersArray];
}

#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Set title
    self.title = [_addressBookGroup groupName];
    
    // BackgroundImageView
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 416.0)];
    [backgroundImageView setImage:[UIImage imageNamed:@"background.png"]];
    [self.view addSubview:backgroundImageView];
    [backgroundImageView release];
    
    // Init ABPersonViewController
    _abPersonViewController = [[ABPersonViewController alloc] init];
    [_abPersonViewController setAllowsEditing:YES];
    [_abPersonViewController setAllowsActions:YES];
    
    // Init tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 372.0)
                                              style:UITableViewStylePlain];
    [_tableView setBackgroundColor:[UIColor clearColor]];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // Footer view
    _footerView = [[UIFooterView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 50.0)];
    [_footerView setDelegate:self];
    
    // Add bar button item
    UIBarButtonItem* addBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPersonButtonHandle:)];
    self.navigationItem.rightBarButtonItem = addBarButtonItem;
    [addBarButtonItem release];
    
    // Tool bar view
    UIToolBarView *toolBarView = [[UIToolBarView alloc] initWithFrame:CGRectMake(0, 372, 320, 44)];
    [toolBarView setDelegate:self];
    [toolBarView setTag:TAG_TOOLBARVIEW];
    [self.view addSubview:toolBarView];
    [toolBarView release];
}

#pragma mark -
#pragma mark Set AddressBookGroup
- (void)setAddressBookGroup:(AddressBookGroup *)addressBookGroup
{
    if(_addressBookGroup != addressBookGroup)
    {
        [_addressBookGroup release];
        
        _addressBookGroup = [addressBookGroup retain];
    }
    
    // Get group members
    NSArray *groupMembersArray = [_addressBookGroup groupMembers];
    
    [_groupMembersArray addObjectsFromArray:groupMembersArray];
    
    [self initGroupMembers:_groupMembersArray];
}

#pragma mark -
#pragma mark Init GroupMembers
- (void)initGroupMembers:(NSArray *)groupMembersArray
{
    if(groupMembersArray)
    {
        [_groupMembersDictionary removeAllObjects];
        [_sectionTitleArray removeAllObjects];
    }
    
    NSMutableDictionary* tempDic = [[NSMutableDictionary alloc] init];
    
    for(int i = 0; i < [groupMembersArray count]; i++)
    {
        AddressBookPerson* addressBookPerson = [groupMembersArray objectAtIndex:i];
        
        for(AddressBookPerson *person in _selectedMemberArray)
        {
            if([[person personName] isEqualToString:[addressBookPerson personName]]) 
            {
                [addressBookPerson setSelected:YES];
            }
        }
        
        NSString* sectionTitle = [self getFirstLetterOfPersonName:[addressBookPerson personName]];
        
        if(nil != sectionTitle)
        {
            if([[tempDic allKeys] containsObject:sectionTitle])
            {
                NSMutableArray* tempArray = [[NSMutableArray alloc] init];
                
                [tempArray addObjectsFromArray:[tempDic objectForKey:sectionTitle]];
                
                [tempArray addObject:addressBookPerson];
                
                [tempDic setObject:tempArray forKey:sectionTitle];
                
                [tempArray release];
            }
            else
            {   
                [tempDic setObject:[NSArray arrayWithObjects:addressBookPerson, nil] 
                            forKey:sectionTitle];
            } 
        }
    }
    
    [_groupMembersDictionary setDictionary:tempDic];
    
    [tempDic release];
    
    NSArray* titleArray = [[NSArray alloc] initWithArray:[[_groupMembersDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)]];
    [_sectionTitleArray setArray:titleArray];
    [titleArray release];
    
    [_tableView reloadData];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sectionTitleArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *keyString = [_sectionTitleArray objectAtIndex:section];
    
    NSArray *memberArray = [_groupMembersDictionary objectForKey:keyString];
    
    return [memberArray count];
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [_sectionTitleArray objectAtIndex:section];
}

- (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if([_sectionTitleArray count] > 5)
    {
        NSMutableArray* sectionIndexTitlesArray = [[NSMutableArray alloc] init];
        
        for(int i = 0; i < [_sectionTitleArray count]; i++)
        {
            [sectionIndexTitlesArray addObject:[_sectionTitleArray objectAtIndex:i]];
        }
        
        return [sectionIndexTitlesArray autorelease];
    }
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{   
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"group member cell";
    
    GroupMemberCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil)
    {
        cell = [[[GroupMemberCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier] autorelease];
        [cell setDelegate:self];
    }
        
    AddressBookPerson* addressBookPerson = [self personForGroupAtIndexPath:indexPath];
    
    if([addressBookPerson selected] == YES)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    [cell setGroupMember:addressBookPerson];
    
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
	GroupMemberCell* cell = (GroupMemberCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    // One person
    AddressBookPerson *addressBookPerson = [self personForGroupAtIndexPath:indexPath];

    if([addressBookPerson selected] == NO)
    {   
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        [addressBookPerson setSelected:YES];
        
		// Add selected member to selectedMemberArray
		[_selectedMemberArray addObject:addressBookPerson];
    }
    else
    {   
        cell.accessoryType = UITableViewCellAccessoryNone;
		
        [addressBookPerson setSelected:NO];
        
		// Remove selected member from m_arraySelectedMember
        for(AddressBookPerson *person in _selectedMemberArray)
        {
            if([person recordID] == [addressBookPerson recordID])
            {
                [_selectedMemberArray removeObject:addressBookPerson];
                break;
            }
        }
    }
}

#pragma mark -
#pragma mark TableView edit DataSource Functions
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{
	return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        NSString* keyString = [_sectionTitleArray objectAtIndex:indexPath.section];
        
        NSMutableArray *personArray = [NSMutableArray arrayWithArray:[_groupMembersDictionary objectForKey:keyString]];
        
        AddressBookPerson* addressBookPerson = [personArray objectAtIndex:indexPath.row];
        
        if([[AddressBookManager sharedManager] removeMember:addressBookPerson fromGroup:_addressBookGroup])
        {   
            if([personArray count] == 1)
            {
                [_groupMembersDictionary removeObjectForKey:keyString];
                
                [_sectionTitleArray removeObjectAtIndex:indexPath.section];
                
                [_groupMembersArray removeObject:addressBookPerson];
                
                [_tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] 
                          withRowAnimation:UITableViewRowAnimationFade];
            }
            else
            {
                [personArray removeObjectAtIndex:indexPath.row];
                [_groupMembersDictionary removeObjectForKey:keyString];
                [_groupMembersDictionary setObject:personArray forKey:keyString];
                
                [_groupMembersArray removeObject:addressBookPerson];
                
                [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
                                  withRowAnimation:UITableViewRowAnimationFade];
            }
        }
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) 
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

#pragma mark -
#pragma mark Add person button handle
- (void)addPersonButtonHandle:(id)sender
{
    AllContactsViewController *allContactsViewController = [[AllContactsViewController alloc] init];
    [allContactsViewController setDelegate:self];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:allContactsViewController];
    [allContactsViewController release];
    [self presentModalViewController:navigationController animated:YES];
    [navigationController release];
}

#pragma mark -
#pragma mark Selected members from all contacts
- (void)didSelectedMembers:(NSMutableArray *)selectedMembers
{   
    for(AddressBookPerson *person in selectedMembers)
    {   
        if([[AddressBookManager sharedManager] addMember:person ToGroup:_addressBookGroup])
        {
            [_groupMembersArray addObject:person];
        }
    }
}

#pragma mark -
#pragma mark UIToolBarView Delegate Method
- (void)toolBarView:(UIToolBarView *)toolBarView didSelectBarButtonAtIndex:(NSInteger)index
{
    UIBarButtonItem *barButtonItem = [toolBarView barButtonItemAtIndex:index];
    
    switch (index)
    {
        case 0: // 选择
        {
            NSArray *keysArray = [_groupMembersDictionary allKeys];
            
            for(int i = 0; i < [keysArray count]; i++)
            {
                NSString *keyString = [keysArray objectAtIndex:i];
                
                NSArray *membersArray = [_groupMembersDictionary objectForKey:keyString];
                
                for(AddressBookPerson *person in membersArray)
                {
                    [person setSelected:!_selectedAll];
                    
                    if(NO == _selectedAll)
                    {
                        [_selectedMemberArray addObject:person];
                    }
                    else
                    {
                        [_selectedMemberArray removeObject:person];;
                    }
                }
            }
            
            [barButtonItem setTitle:(_selectedAll == YES ? NSLocalizedString(@"全选", nil) : NSLocalizedString(@"取消", nil))];
            UIBarButtonItem *editBarButtonItem = [toolBarView barButtonItemAtIndex:3];
            editBarButtonItem.enabled = _selectedAll;
            
            _selectedAll = !_selectedAll;
            
            [_tableView reloadData];
        }
            break;
        case 1: // 短信
        {    
            if(_selectedMemberArray && [_selectedMemberArray count] != 0)
            {   
                [[UIStatusWindow sharedStatusWindow] show:NSLocalizedString(@"正在筛选联系人手机号码", nil)];
                
                NSMutableArray *phoneNumberArray = [[[NSMutableArray alloc] init] autorelease];
                
                for(AddressBookPerson *person in _selectedMemberArray)
                {
                    NSDictionary *phoneDic = [person personPhone];
                    
                    if(phoneDic && [phoneDic count] != 0)
                    {
                        // Mobile
                        NSString *mobileNumber = [phoneDic objectForKey:MOBILE_LABEL];
                        if(mobileNumber)
                        {
                            [phoneNumberArray addObject:mobileNumber];
                        }
                        
                        // iPhone
                        NSString *iPhoneNumber = [phoneDic objectForKey:IPHONE_LABEL];
                        if(iPhoneNumber)
                        {
                            [phoneNumberArray addObject:iPhoneNumber];
                        }
                    }
                }
                
                [self performSelector:@selector(sendShortMessage:) 
                           withObject:phoneNumberArray 
                           afterDelay:0.1];
            }
            else
            {
                UIAlertView *noMemberAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"请先选择联系人", nil)
                                                                        message:nil
                                                                       delegate:nil
                                                              cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                              otherButtonTitles:nil];
                [noMemberAlert show];
                [noMemberAlert release];
            }
        }
            break;
        case 2: // 邮件
        {   
            if(_selectedMemberArray && [_selectedMemberArray count] != 0)
            {
                [[UIStatusWindow sharedStatusWindow] show:NSLocalizedString(@"正在筛选联系人邮件地址", nil)];
                
                NSMutableArray *emailAddressArray = [[[NSMutableArray alloc] init] autorelease];
                
                for(AddressBookPerson *person in _selectedMemberArray)
                {
                    NSDictionary *phoneDic = [person personEmail];
                    
                    if(phoneDic && [phoneDic count] != 0)
                    {
                        // Home email address
                        NSString *homeEmailAddressString = [phoneDic objectForKey:HOME_LABEL];
                        if(homeEmailAddressString)
                        {
                            [emailAddressArray addObject:homeEmailAddressString];
                        }
                        
                        // work email address 
                        NSString *workEmailAddressString = [phoneDic objectForKey:WORK_LABEL];
                        if(workEmailAddressString)
                        {
                            [emailAddressArray addObject:workEmailAddressString];
                        }
                    }
                }
                
                [self performSelector:@selector(sendEMail:) 
                           withObject:emailAddressArray 
                           afterDelay:0.1];
            }
            else
            {
                UIAlertView *noMemberAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"请先选择联系人", nil)
                                                                        message:nil
                                                                       delegate:nil
                                                              cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                              otherButtonTitles:nil];
                [noMemberAlert show];
                [noMemberAlert release];
            }
        }
            break;
        case 3: // 编辑
        {
            UIBarButtonItem *selectAllBarButtonItem = [toolBarView barButtonItemAtIndex:0];
            if(YES == _tableView.editing)
            {
                selectAllBarButtonItem.enabled = YES;
                _tableView.tableFooterView = nil;
                [barButtonItem setStyle:UIBarButtonItemStyleBordered];
                [barButtonItem setTitle:NSLocalizedString(@"编辑", nil)];
            }
            else
            {
                selectAllBarButtonItem.enabled = NO;
                _tableView.tableFooterView = _footerView;
                [barButtonItem setStyle:UIBarButtonItemStyleDone];
                [barButtonItem setTitle:NSLocalizedString(@"完成", nil)];
            }
            [_tableView setEditing:!_tableView.editing animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark Send short message
- (void)sendShortMessage:(NSArray *)phoneNumberArray
{    
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
    
    [[UIStatusWindow sharedStatusWindow] hide];
    
    if (messageClass != nil && [messageClass canSendText]) 
    { 	
        // MFMessageComposeViewController
        MFMessageComposeViewController *messageComposeViewController = [[MFMessageComposeViewController alloc] init];
        messageComposeViewController.navigationBar.tintColor = TINT_COLOR;
        [messageComposeViewController setMessageComposeDelegate:self];
        [messageComposeViewController setRecipients:phoneNumberArray];
        [self presentModalViewController:messageComposeViewController animated:YES];
        [messageComposeViewController release];
    }
    else 
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"抱歉", nil)
                                                        message:NSLocalizedString(@"您的设备不支持发短信功能!", nil) 
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

#pragma mark -
#pragma mark Send email
- (void)sendEMail:(NSArray *)emailAddressArray
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
    [[UIStatusWindow sharedStatusWindow] hide];
    
    if (mailClass != nil)
    {
        if([mailClass canSendMail])
        {   
            // MFMailComposeViewController
            MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init];
            mailComposeViewController.navigationBar.tintColor = TINT_COLOR;
            [mailComposeViewController setMailComposeDelegate:self];
            [mailComposeViewController setToRecipients:emailAddressArray];
            [self presentModalViewController:mailComposeViewController animated:YES];
            [mailComposeViewController release];
        }
        else
        {
            // 如果没有绑定邮箱
            NSMutableString *addressString = [[NSMutableString alloc] init];
            
            for(int i = 0; i < [emailAddressArray count]; i++)
            {
                if(0 == i)
                {
                    [addressString appendString:[emailAddressArray objectAtIndex:i]];
                }
                else
                {
                    [addressString appendString:@","];
                    [addressString appendString:[emailAddressArray objectAtIndex:i]];
                }
            }
            
            NSString* strEmail = [NSString stringWithFormat:@"mailto:%@", addressString];
            [addressString release];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strEmail]];
        }
    }
    else
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"抱歉", nil)
                                                        message:NSLocalizedString(@"您的设备不支持发邮件功能!", nil)
                                                       delegate:nil 
                                              cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}

#pragma mark -
#pragma mark GroupMemberCell:didSelectedPerson:
- (void)groupMemberCell:(GroupMemberCell *)cell didSelectedPerson:(AddressBookPerson *)addressBookPerson
{
    _abPersonViewController.displayedPerson = [addressBookPerson record];
    [self.navigationController pushViewController:_abPersonViewController animated:YES];
}

#pragma mark -
#pragma mark Delete group button
- (void)didSelected:(UIFooterView *)footerView
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                               destructiveButtonTitle:NSLocalizedString(@"删除群组", nil)
                                                    otherButtonTitles:nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
    [actionSheet release];
}

#pragma mark -
#pragma mark actionSheet delegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(0 == buttonIndex)
    {
        if([[AddressBookManager sharedManager] removeGroup:_addressBookGroup])
        {   
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"删除群组失败", nil)
                                                                message:nil
                                                               delegate:nil
                                                      cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
    }
}

//#pragma mark -
//#pragma mark UIAlertView delegate methods
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{	
//	if([alertView.title isEqualToString:@"发送报告"])
//	{
//		if(alertView.tag == 100)
//		{	
//			if(buttonIndex == 0)
//			{	
//				[self dismissModalViewControllerAnimated:YES];
//			}
//			else
//			{	
//                //	[self dismissModalViewControllerAnimated:YES];
//				
//				[self.navigationController popToRootViewControllerAnimated:YES];
//			}
//		}
//		else
//		{
//            //	[self dismissModalViewControllerAnimated:YES];
//		}
//	}
//}

#pragma mark -
#pragma mark MessageComposeViewController delegate method
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result 
{	
	switch (result)
	{
		case MessageComposeResultCancelled:
		{
			[self dismissModalViewControllerAnimated:YES];
		}
			break;
		case MessageComposeResultSent:
		{
			[self dismissModalViewControllerAnimated:YES];
			
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"发送报告", nil)
                                                            message:NSLocalizedString(@"短信正在发送,感谢您的使用!", nil) 
                                                           delegate:nil 
                                                  cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
			break;
		case MessageComposeResultFailed:
		{
			[self dismissModalViewControllerAnimated:YES];
			
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"发送报告", nil)
                                                            message:NSLocalizedString(@"发送失败,请重新操作!", nil)
                                                           delegate:nil 
                                                  cancelButtonTitle:NSLocalizedString(@"好的", nil)
                                                  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
			break;
		default:
			//strSendResult = @"SMS not sent.";
			break;
	}
}

#pragma mark -
#pragma mark MFMailComposeViewController delegate method
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Private Methods
#pragma mark -
#pragma mark personForGroupAtIndexPath
- (AddressBookPerson *)personForGroupAtIndexPath:(NSIndexPath *)indexPath;
{
    NSString* keyString = [_sectionTitleArray objectAtIndex:indexPath.section];
    
    NSArray* personArray = [_groupMembersDictionary objectForKey:keyString];
    
    return [personArray objectAtIndex:indexPath.row];
}

#pragma mark -
#pragma mark searchResult:searchText:
- (BOOL)searchResult:(NSString*)personName searchText:(NSString *)searchText
{
	NSComparisonResult result = [personName compare:searchText 
                                            options:NSCaseInsensitiveSearch 
                                              range:NSMakeRange(0, searchText.length)];
	if(result == NSOrderedSame)
    {
		return YES;
    }
	
    return NO;
}

#pragma mark -
#pragma mark getFirstLetterOfPersonName
- (NSString*)getFirstLetterOfPersonName:(NSString*)strPersonName
{   
	if(0 != [strPersonName length])
	{
		if([self searchResult:strPersonName searchText:@"曾"])
			return @"Z";
		else if([self searchResult:strPersonName searchText:@"查"])
			return @"Z";
		else if([self searchResult:strPersonName searchText:@"仇"])
			return @"Q";
		else if([self searchResult:strPersonName searchText:@"朴"])
			return @"P";
		else if([self searchResult:strPersonName searchText:@"能"])
			return @"N";
		else if([self searchResult:strPersonName searchText:@"乐"])
			return @"Y";
		else if([self searchResult:strPersonName searchText:@"单"])
			return @"S";
		else if([self searchResult:strPersonName searchText:@"解"])
			return @"X";
		else if([self searchResult:strPersonName searchText:@"沈"])
			return @"S";
		else
		{
            
			unsigned short nChinese = 0;
            
            nChinese = [strPersonName characterAtIndex:0];
			
//            if((nChinese >= 65 && nChinese <= 90) || (nChinese >= 97 && nChinese <= 122))
//            {
                return [[NSString stringWithFormat:@"%c", getPinYinFirstLetterFromChinese(nChinese)] uppercaseString];
//            }
//            else
//            {
//                return @"#";
//            }
		}	
	}
	
	return nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
